{% extends 'layout.html' %}

{% block content %}
    <div class="container">
        <div style="margin-bottom: 10px" class="clearfix">
            <a class="btn btn-success" id="btnAdd">
                <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
                新建订单
            </a>
            <div style="float: right; width: 300px">
                <form method="get">
                    <div class="input-group">
                        <input type="text" class="form-control" name="q" placeholder="订单号搜索"
                               value="{{ search_data }}">
                        <span class="input-group-btn">
                        <button class="btn btn-default" type="submit">
                            <span class="glyphicon glyphicon-search" aria-hidden="true"></span> 查询
                        </button>
                    </span>
                    </div><!-- /input-group -->
                </form>
            </div>

        </div>

        <div class="panel panel-default">
            <!-- 面板标题 -->
            <div class="panel-heading">
                <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
                订单列表
            </div>

            <!-- 面板表格部分 -->
            <table class="table table-bordered">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>订单号</th>
                    <th>商品名称</th>
                    <th>价格</th>
                    <th>状态</th>
                    <th>管理员</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                {% for obj in queryset %}
                    <tr uid="{{ obj.id }}">
                        <th scope="row">{{ obj.id }}</th>
                        <td>{{ obj.oid }}</td>
                        <td>{{ obj.title }}</td>
                        <td>{{ obj.price }}</td>
                        <td>{{ obj.get_status_display }}</td>
                        <td>{{ obj.admin }}</td>
                        <td>
                            {# <a class="btn btn-primary btn-xs" href="/order/{{ obj.id }}/edit/">编辑</a>#}
                            <input uid="{{ obj.id }}" type="button" class="btn btn-primary btn-xs btn-edit"
                                   value="编辑">
                            {# <a class="btn btn-danger btn-xs" href="/order/{{ obj.id }}/delete/">删除</a>#}
                            <input uid="{{ obj.id }}" type="button" class="btn btn-danger btn-xs btn-delete"
                                   value="删除">
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
        <ul class="pagination">
            {{ page_string }}
        </ul>
    </div>

    <!-- 新建/编辑订单弹窗 -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">新建订单</h4>
                </div>
                <div class="modal-body">

                    <form id="formAdd">
                        <div class="clearfix">
                            {% for field in form %}
                                <div class="col-xs-6">
                                    <div class="form-group" style="position: relative; margin-bottom: 20px">
                                        <label>{{ field.label }}</label>
                                        {{ field }}
                                        <span class="error-msg" style="color: red;position: absolute;"></span>
                                    </div>
                                </div>
                            {% endfor %}

                        </div>
                    </form>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button id="btnSave" type="button" class="btn btn-primary">保存</button>
                </div>
            </div>
        </div>

    </div>

    <!-- 删除（对话框） -->
    <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="alert alert-danger alert-dismissible fade in" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
                        aria-hidden="true">×</span></button>
                <h4>确认删除？</h4>
                <p style="margin: 10px 0px;">删除操作，数据丢失不可逆，请谨慎操作</p>
                <p style="text-align: right">
                    <button id="btnConfirmDelete" type="button" class="btn btn-danger">确认</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                </p>
            </div>
        </div>
    </div>

{% endblock %}

{% block js %}
    <script type="text/javascript">
        var DELETE_ID;
        var EDIT_ID;
        $(function () {
            bindBtnAddEvent();
            bindBtnSaveEvent();
            bindBtnDeleteEvent();
            bindBtnConfirmDeleteEvent();
            bindBtnEditEvent();
        })

        function bindBtnAddEvent() {
            $("#btnAdd").click(function () {
                //将正在编辑的ID设置为空
                EDIT_ID = undefined;
                //清空对话框中的数据
                $("#formAdd")[0].reset();

                // 修改对话框的标题
                $("#myModalLabel").text("新建订单");
                // 点击新建按钮，显示对话框
                $('#myModal').modal('show');
            });
        }

        function bindBtnSaveEvent() {
            $("#btnSave").click(function () {
                // 点击之前，先清除所有错误信息
                $(".error-msg").empty();

                if (EDIT_ID) {
                    //编辑
                    doEdit();
                } else {
                    //添加
                    doAdd();
                }

            });
        }

        function doAdd() {
            // 发送ajax请求(这是添加订单的Ajax请求)
            $.ajax({
                url: "/order/add/",
                type: "post",
                data: $("#formAdd").serialize(),
                dataType: "JSON",
                success: function (res) {
                    if (res.status) {
                        //alert("创建成功");
                        //清空表单
                        $("#formAdd")[0].reset();
                        // 关闭对话框
                        $('#myModal').modal('hide');
                        // 刷新页面
                        location.reload();
                    } else {
                        // 创建失败，展示错误信息
                        $.each(res.error, function (name, errorList) {
                            $("#id_" + name).next().text(errorList[0]);
                        })
                    }
                }
            })
        }

        function doEdit() {
            // 发送ajax请求(这是编辑订单的Ajax请求)
            $.ajax({
                url: "/order/edit/" + "?uid=" + EDIT_ID,  // ===>   /order/edit/?uid=123
                type: "post",
                data: $("#formAdd").serialize(),
                dataType: "JSON",
                success: function (res) {
                    if (res.status) {
                        //清空表单
                        $("#formAdd")[0].reset();
                        // 关闭对话框
                        $('#myModal').modal('hide');
                        // 刷新页面
                        location.reload();
                    } else {
                        if (res.tips) {
                            alert(res.tips);
                        } else {
                            // 创建失败，展示错误信息
                            $.each(res.error, function (name, errorList) {
                                $("#id_" + name).next().text(errorList[0]);
                            })
                        }

                    }
                }
            })
        }

        function bindBtnDeleteEvent() {
            $(".btn-delete").click(function () {
                // 显示删除对话框
                $("#deleteModal").modal('show');
                // 获取当前行的id,并赋值给全局变量
                DELETE_ID = $(this).attr("uid");
                console.log(DELETE_ID);
            });
        }

        function bindBtnConfirmDeleteEvent() {
            $("#btnConfirmDelete").click(function () {
                //点击确认删除按钮，将全局变量中设置的那个要删除ID发送到后台
                $.ajax({
                    url: "/order/delete/",  //  ==> /order/delete/?uid=123
                    type: "get",
                    data: {
                        uid: DELETE_ID
                    },
                    dataType: "JSON",
                    success: function (res) {
                        if (res.status) {
                            //删除成功，隐藏删除对话框
                            //$("#deleteModal").modal('hide');
                            //在页面上把当前一行数据删掉（js）
                            //$("tr[uid='" + DELETE_ID + "']").remove();
                            //要删除的id置空
                            //DELETE_ID = 0;
                            //更简单的思路：删除成功直接刷新页面
                            location.reload();
                        } else {
                            //删除失败
                            alert(res.error);
                        }

                    }
                })
            });
        }

        function bindBtnEditEvent() {
            $(".btn-edit").click(function () {
                //清空对话框中的数据
                $("#formAdd")[0].reset();
                //清除错误信息
                {#$(".error-msg").empty();#}

                // 当前行的id
                var uid = $(this).attr("uid")
                EDIT_ID = uid;
                //发送Ajax去后端获取当前行的相关数据 /order/detail/?uid=123
                $.ajax({
                    url: "/order/detail/",
                    type: "get",
                    data: {
                        uid: uid
                    },
                    dataType: "JSON",
                    success: function (res) {
                        if (res.status) {
                            // 获取后端数据成功，将数据赋值给对话框的标签中
                            // $("#id_"+name)   找到标签
                            // .val()   给input赋值
                            $.each(res.data, function (name, value) {
                                $("#id_" + name).val(value);
                            })

                            // 修改对话框的标题
                            $("#myModalLabel").text("编辑订单");
                            //点击编辑，显示模态对话框
                            $('#myModal').modal('show');
                        } else {
                            alert(res.error);
                        }
                    }
                })


            });
        }
    </script>

{% endblock %}
